package registry

import (
	"barge/app"
	"barge/pkg/uix"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"strings"
)

// setCmd represents the base command when called without any subcommands
var setCmd = &cobra.Command{
	Use:   "set",
	Short: "设置镜像仓库信息",
	Long: `
示例: barge R set registry --addr=registry.example.com --username=admin --password=123456 -A amd64 -A arm64
`,
	Args: func(cmd *cobra.Command, args []string) error {
		if registry.Name == "" && len(args) > 0 {
			registry.Name = args[0]
		}

		if viper.GetBool("interactive") {
			if registry.Name == "" {
				registry.Name = uix.Input("请输入镜像仓库名称：")
			}
			if registry.Name == "" {
				return errors.New("镜像仓库名称不能为空")
			}
			if registry.Address == "" {
				registry.Address = uix.Input("请输入镜像仓库地址：")
			}
			if registry.Address == "" {
				return errors.New("镜像仓库地址不能为空")
			}
			if registry.Username == "" {
				registry.Username = uix.Input("请输入镜像仓库用户：")
			}
			if registry.Password.Raw == "" {
				registry.Password.Raw = uix.Input("请输入镜像仓库密码：")
			}
			if registry.Architectures == nil {
				architectures := uix.Input("请输入镜像仓库架构,使用 , 分割多个架构：")
				registry.Architectures = strings.Split(architectures, ",")
			}
		}

		if registry.Name == "" {
			return errors.New("镜像仓库名称不能为空")
		}
		if registry.Address == "" && registry.Acp == "" {
			return errors.New("镜像仓库地址不能为空")
		}
		if registry.Acp == "" && registry.Architectures == nil {
			return errors.New("镜像仓库架构非ACP获取时不能为空")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		m, err := app.NewConfigManager(viper.GetString("configPath"))
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
		m.SetRegistry(registry)
		err = m.Save()
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
	},
}

var registry = new(app.RegistryOption)

func init() {
	registryCmd.AddCommand(setCmd)
	setCmd.Flags().StringVarP(&registry.Name, "name", "n", "", "镜像仓库名称")
	setCmd.Flags().StringVarP(&registry.Address, "addr", "a", "", "镜像仓库地址")
	setCmd.Flags().StringVarP(&registry.Acp, "acp", "", "", "ACP IP地址")
	setCmd.Flags().StringVarP(&registry.Token, "token", "", "", "ACP token")
	setCmd.Flags().StringVarP(&registry.Cluster, "cluster", "c", "global", "集群名称")
	setCmd.Flags().StringVarP(&registry.Username, "username", "u", "", "镜像仓库名称用户")
	setCmd.Flags().StringVarP(&registry.Password.Raw, "password", "p", "", "镜像仓库名称密码")
	setCmd.Flags().StringArrayVarP(&registry.Architectures, "arch", "A", nil, "镜像仓库架构: [amd64,arm64]")
}
